package com.chenxin.wms.process.outbound.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.annotation.WmsLogs;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.enums.WmsBusinessStatus;
import com.chenxin.common.enums.WmsTaskSubType;
import com.chenxin.common.enums.WmsTaskType;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.wms.domain.ObDetailEntity;
import com.chenxin.wms.domain.StockEntity;
import com.chenxin.wms.domain.TaskEntity;
import com.chenxin.wms.mapper.ObDetailMapper;
import com.chenxin.wms.mapper.StockMapper;
import com.chenxin.wms.mapper.TaskMapper;
import com.chenxin.wms.process.outbound.IProcPrepareCancelByDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class ProcPrepareCancelByDetail implements IProcPrepareCancelByDetail {
    @Autowired
    private ObDetailMapper obDetailMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private StockMapper stockMapper;

    @Override
    @Transactional
    @WmsLogs(name = "出库明细取消备货")
    public ProcResult call(Long obDetailId, Long creator) {
        // 根据明细ID获取所需信息（明细、主单、物料等）
        if (StringUtils.isNull(obDetailId)) {
            return ProcResult.error("pre_cancel_err001", "明细ID不能为空");
        }
        ObDetailEntity obDetail = obDetailMapper.selectById(obDetailId);
        if (obDetail == null) {
            return ProcResult.error("pre_cancel_err002", "明细ID【" + obDetailId + "】不存在");
        }
        // 单据状态大于2无法取消备货
        if (obDetail.getObDetailStatus() > WmsBusinessStatus.OB_DETAIL_PREPARED.getCode()) {
            return ProcResult.error("pre_cancel_err003", "单据当前状态【" + obDetail.getObDetailStatus() + "】无法取消备货");
        }
        // 检索明细对应备货任务（初始状态的任务允许取消）
        QueryWrapper<TaskEntity> preTaskQW = new QueryWrapper<>();
        preTaskQW.lambda().eq(TaskEntity::getDetailId, obDetailId)
                .eq(TaskEntity::getMasterId, obDetail.getObMasterId())
                .eq(TaskEntity::getTaskType, WmsTaskType.SHIPMENT_OUT.getCode())
                .eq(TaskEntity::getTaskSubType, WmsTaskSubType.PREPARE_OUT.getCode())
                .eq(TaskEntity::getTaskStatus, WmsConstants.TASK_STATUS_INIT);
        List<TaskEntity> cancelTasks = taskMapper.selectList(preTaskQW);
        if (cancelTasks == null || cancelTasks.size() == 0) {
            return ProcResult.error("pre_cancel_err004", "明细【" + obDetailId + "】无待取消的备货任务！所属出库主单【" + obDetail.getObMasterId() + "】");
        }
        // 循环处理备货任务
        for (TaskEntity task : cancelTasks) {
            // 更新任务状态为取消4
            task.setTaskStatus(WmsConstants.TASK_STATUS_CANCEL);
            task.setComments("取消备货任务");
            task.setUpdater(creator);
            task.setUpdateDate(new Date());

            taskMapper.updateById(task);

            // 处理对应库存
            StockEntity cancelStock = stockMapper.selectById(task.getStockId());
            if (cancelStock == null) {
                return ProcResult.error("pre_cancel_err005", "关联库存【" + task.getStockId() + "】不存在！");
            }
            // 备货数量在预分配数量上扣减
            cancelStock.setLockedQty(cancelStock.getLockedQty().subtract(task.getPlanQty()));
            // 预分配数量=0则库存状态为空闲，否则为占用
            cancelStock.setStockStatus(WmsConstants.STOCK_STATUS_IDLE);
            cancelStock.setUpdater(creator);
            cancelStock.setUpdateDate(new Date());
            stockMapper.updateById(cancelStock);

            // 处理出库明细（扣减绑定数量）
            BigDecimal bindQty = obDetail.getObBindQty().subtract(task.getPlanQty());
            obDetail.setObBindQty(bindQty);
            obDetail.setComments("取消备货");
            obDetail.setUpdater(creator);
            obDetail.setUpdateDate(new Date());
            if (bindQty.compareTo(BigDecimal.ZERO) > 0) {
                obDetail.setObDetailStatus(WmsBusinessStatus.OB_DETAIL_PREPARING.getCode());
            } else {
                obDetail.setObDetailStatus(WmsBusinessStatus.OB_DETAIL_INIT.getCode());
            }
            obDetailMapper.updateById(obDetail);
        }
        // TODO 处理主单状态
        return ProcResult.success("出库明细【" + obDetailId + "】备货取消成功!所属出库主单【" + obDetail.getObMasterId() + "】");
    }
}
